<?php

    class FilesController extends Application {

        function setup()
        {
            $this->actions = array('index','add','delete','file_types',
                                   'add_file_type','delete_file_type',
                                   'browse','crop_image');
            $this->use_layout('admin_layout.php');
            $this->before_filter('is_logged_in');
            $this->before_filter('has_access');
            use_model('files','file_folders','file_types');
            
        }
        
        function has_access()
        {
            if (!has_access_to('Files::Access Files')) {
                flash('error','Sorry but you do not have access to the Files tool');
                $this->redirect_to(array('controller'=>'admin/dashboard'));
             }
        }
        
		function index() 
		{
		    $files =& new Files();
		    $this->assign_ref('files',$files);
		    
		    $folders =& new File_Folders();
		    $this->assign_ref('folders',$folders);		 
		    
		    // type filters
		    if ( isset($_REQUEST['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = htmlspecialchars($_REQUEST['files_filter_by']);
		    }
		    
		    if ( empty($_SESSION['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = 'all';
		    }
		    
		    $this->assign('file_filters',$files->get_filters());
		    $this->assign('file_filter_selected', $_SESSION['files_filter_by']);   		    
		    
		    // get all folders
		    $file_folder_id = isset($_REQUEST['file_folder_id']) ? (int) $_REQUEST['file_folder_id'] : 1 ;
		    $this->assign('file_folder_id',$file_folder_id);
		    $this->assign('all_files', $files->get_files_by_folder($file_folder_id, 
		                                                          $_SESSION['files_filter_by']));
		    $this->assign('all_folders', $folders->get_sub_folders($file_folder_id));
		    $this->assign('folder_path',$folders->get_breadcrumb($file_folder_id));
		    $this->assign('redirect','index');
		    		    
		}
		
		function browse() 
		{
		    $this->use_layout('filebrowser_layout.php');
		    $files =& new Files();
		    $this->assign_ref('files',$files);
		    
		    $folders =& new File_Folders();
		    $this->assign_ref('folders',$folders);	
		    
		    // type filters
		    if ( isset($_REQUEST['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = htmlspecialchars($_REQUEST['files_filter_by']);
		    }
		    
		    if ( empty($_SESSION['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = 'all';
		    }
		    
		    $this->assign('file_filters',$files->get_filters());
		    $this->assign('file_filter_selected', $_SESSION['files_filter_by']);	    		    
		    
		    // get all folders
		    $file_folder_id = isset($_REQUEST['file_folder_id']) ? (int) $_REQUEST['file_folder_id'] : 1 ;
		    $this->assign('file_folder_id',$file_folder_id);
		    $this->assign('all_files', $files->get_files_by_folder($file_folder_id, 
		                                                            $_SESSION['files_filter_by']));
		    $this->assign('all_folders', $folders->get_sub_folders($file_folder_id));
		    $this->assign('folder_path',$folders->get_breadcrumb($file_folder_id));
		    $this->assign('redirect','browse');		    
		    
		}
        
		
		function add()
		{
		    if ( $_POST['action'] == 'add_file' && has_access_to('Files::Upload Files') )
		    {
		        $files =& new Files();
		        if ( $files->update_fields($_POST['files']) )
		        {
		            flash('notice','File Uploaded');
		        } else {
		            $errors = implode('<br>',$files->get_errors_on('File'));
		            flash('error','Error: '.$errors);
		        }
		    }
		    
		    if ( $_POST['action'] == 'add_folder' && has_access_to('Files::Create Folders') )
		    {
		        $folders =& new File_Folders();
		        if ( $folders->update_fields($_POST['folders']) )
		        {
		            flash('notice','Folder Created');
		        } else {
		            $errors = implode('<br>',$folders->get_errors_on('name'));
		            flash('error','Error: '.$errors);
		        }
		    }
		    $redirect = isset($_POST['redirect']) ? htmlspecialchars($_POST['redirect']) : 'index';
		    $this->redirect_to(array('controller'=>'admin/files' ,
		                            'action'=>$redirect.'?file_folder_id='.$_POST['file_folder_id']));
		}
		
		function delete()
		{
		    if ( $_POST['action'] == 'delete_file' && has_access_to('Files::Delete Files') )
		    {
		        $files =& new Files();
		        if ( $files->delete_file($_POST['id']) )
		        {
		            flash('notice','File Deleted');
		        }
		    }
		    
		    if ( $_POST['action'] == 'delete_folder' && has_access_to('Files::Delete Folders') )
		    {
		        $folders =& new File_Folders();
		        if ( $folders->delete_folder($_POST['id']) )
		        {
		            flash('notice','Folder Deleted');
		        }
		    }
		    $redirect = isset($_POST['redirect']) ? $_POST['redirect'] : 'index';
		    $this->redirect_to(array('controller'=>'admin/files' ,
		                        'action'=>$redirect.'?file_folder_id='.$_POST['file_folder_id']));
		}

        function file_types()
        {
            $types = new File_Types();
            $this->assign('all_types',$types->get_allowed_types());
            $this->assign_ref('types',$types);
        }
        
        function add_file_type()
        {
            if ( !has_access_to('Files::Modify File Types') )
            {
                $this->redirect_to('index');
            }
            if ( $_POST['action'] == 'add_file_type' )
            {
                $types = new File_Types();
                if ( $types->update_fields($_POST['types']) )
                {
                    flash('notice','File Type Added');
                    $this->assign('type',$types->fields);
                    $this->render(array('partial'=>'_list.php'));
                    return;
                } else {
                    foreach( $types->get_errors() as $key => $value )
            		{
            			$errors .= "$key: ".implode("<br>",$value);
            		}
                    $this->assign('error',$errors);
                    $this->render(array('partial'=>'_error.php'));
                }
            }
            $this->redirect_to('file_types');
        }
        
        function delete_file_type()
        {
            if ( !has_access_to('Files::Modify File Types') )
            {
                $this->redirect_to('index');
            }
            if ( $_POST['action'] == 'delete_file_type' )
            {
                $types = new File_Types();
                $id    = (int) $_POST['id'];
                if ( $types->load($id) )
                {
                    $types->delete();
                    flash('notice','File Type Deleted');
                    $this->render( array('inline'=>'File Type Deleted')  );
                    return;
                }
            }
            $this->redirect_to('file_types');
        }
        
        function crop_image()
        {
            // crop the image using the prototype js thing and phpthumb.
            if ( !isset($_POST['id']) )
            {
                $this->redirect_crop_error('Invalid File Id Specified.');
            }
            
            // load the file
            $file_id = (int) $_POST['id'];
            $file_folder_id = (int) $_POST['file_folder_id'];
            $files   = new Files();
            $files->load($file_id);            
            if ( !$files->is_loaded() )
            {
                $this->redirect_crop_error('File could not be loaded.', $file_folder_id);
            }
            
            // if the file is not an image type, redirect to index
            $mime_type = $files->get('type');
            if ( !preg_match("!^image/!i",$mime_type) )
            {
                $this->redirect_crop_error('Sorry, you can only crop image files.', $file_folder_id);
            }
            
            // jpg fix
            $jpegs = array('image/jpeg','image/jpg','image/pjpeg');
            if(in_array($mime_type, $jpegs)){
                $mime_type = 'image/jpeg';   
            }
            // path to file will return with a / in the front fyi
            $file_folders = new File_Folders();
            $path_to_file = path_to_file($files->get('file_folder_id'));  
            $server_path_to_file = $file_folders->get_server_path($files->get('file_folder_id'));

            // template stuff			
            $this->assign('server_path_to_file',$server_path_to_file);
            $this->assign('image',$files->fields);
            $this->assign('file_folder_id', $file_folder_id);
            $this->assign('public_path_to_file', $path_to_file);
            
            // ok time to process the requested dimensions
            if ( isset($_POST['modify_image']) )
            {            
                $image = $files->fields; // just easier than using get
                
                // create php thumb instance and get jiggy with it.
                require VENDOR .'/phpthumb/phpthumb.class.php';
                $phpThumb = new phpThumb();
                $phpThumb->setSourceFilename($server_path_to_file.'/'.$files->get('name'));
            
                // set output type
                $phpThumb->config_output_format = str_replace('image/','',$mime_type);
                $phpThumb->aoe = 1; // allow output enlargement
            
                // crop or resize
                switch($_POST['action']){                    
                    case 'crop':                        
                        $phpThumb->sx = (int) $_POST['x1'];
                        $phpThumb->sy = (int) $_POST['y1'];
                        $phpThumb->sw = (int) $_POST['c_width'];
                        $phpThumb->sh = (int) $_POST['c_height'];
                        $newW         = (int) $_POST['c_width'];
                        $newH         = (int) $_POST['c_height'];
                        $file_name_action = 'crop';
                        break;                    
                    case 'resize':
                        $phpThumb->w = (int) $_POST['r_width'];
                        $phpThumb->h = (int) $_POST['r_height'];
                        $newW        = (int) $_POST['r_width'];
                        $newH        = (int) $_POST['r_height'];
                        $file_name_action = 'resize';
                        break;
                }
            
                // save file as a new file, then input into db
                if(isset($_POST['save_as_new'])){                                        
                    // create a new filename
                    $ext         = $image['ext'];
                    $rawname     = strtolower(substr($image['name'], 0, strrpos($image['name'], '.')));
                    $rawname     = preg_replace('/[^\w.-]/', '_',$rawname); // make safe
                    $uniqid      = uniqid("_{$newW}x{$newH}_");
                    $newfilename = "{$rawname}_{$file_name_action}{$uniqid}.{$ext}";                    
                    if ($phpThumb->GenerateThumbnail()) {
                        if (!$phpThumb->RenderToFile($server_path_to_file.'/'.$newfilename)) {
                            error_log(print_r($phpThumb->debugmessages,1));
                            flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                            return;
                        }
                    } else {
                        error_log(print_r($phpThumb->debugmessages,1));
                        flash('error','There was a fatal error in the image processing, please view the error logs for the output');
                        return;
                    }
                    @chmod($server_path_to_file.'/'.$newfilename, 0755);
                
                    // insert into db 
                    $new_file = new Files();
                    $new_file->is_file_upload = false;
                    $new_file->set('name', $newfilename);
                    $new_file->set('size', filesize($server_path_to_file . '/'. $newfilename));
                    $new_file->set('type', $mime_type);
                    $new_file->set('file_folder_id', $files->get('file_folder_id'));
                    $new_file->set('ext', $files->get('ext'));
                    if ( $new_file->save() )
                    {
                        flash('notice', 'Modified image saved');
                    } else {
                        flash('error','Modification of image failed.'.print_r($new_file->get_errors(),1) );
                    }
                                                 
                } else {
                    // save file
                    if ( $phpThumb->GenerateThumbnail() ) 
                    {
                        if ( !$phpThumb->RenderToFile($server_path_to_file.'/'.$files->get('name')) ) 
                        {
                            error_log(print_r($phpThumb->debugmessages,1));
                            flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                            return;
                        } 
                    } else {
                        error_log(print_r($phpThumb->debugmessages,1));
                        flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                        return;
                    }
                    flash('notice','Image Saved');
                    @chmod($server_path_to_file.'/'.$files->get('name'), 0755);
                }
                header('Expires: Mon, 26 Jul 1997 05:00:00 GMT') ;
                // always modified
                header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT') ;
                // HTTP/1.1
                header('Cache-Control: no-store, no-cache, must-revalidate') ;
                header('Cache-Control: post-check=0, pre-check=0', false) ;
                // HTTP/1.0
                header('Pragma: no-cache') ;                
    		    $this->redirect_to(array('controller'=>'admin/files' ,
    		                            'action'=>'index?file_folder_id='.$_POST['file_folder_id']));
            }            
        }
        
        function redirect_crop_error($msg,$file_folder_id=0)
        {
            flash('error',$msg);
            $this->redirect_to('index?'.$file_folder_id);
        }
    }

?>